<?php

namespace Biz\service\trade;

use Biz\model\course\CourseOrder as mCourseOrder;
use Biz\model\course\CourseOrderLog as mCourseOrderLog;
use Biz\model\package\PackageOrder;
use Biz\model\package\PackageOrderLog;
use Biz\model\trade\OrderParent;
use Biz\module\Classes\OrderInfo;
use Biz\module\Packages\Pay\IAP;
use Biz\module\Packages\Pay\Tiles as pTiles;
use Biz\service\course\CourseOrder;
use Biz\service\Group;
use Biz\service\redPacket\RedPackets;
use Biz\service\Tiles;
use Biz\tools\OrderNo;
use Doraemon\tools\Log;
class PaySuccess
{

    /**
     * 订单支付成功页面
     * @param $uid
     * @param $orderNo
     * @return \stdClass
     */
    public static function main($uid, $orderNo)
    {
        $response = new \stdClass();
        $response->order_no = $orderNo;
        $response->pay_amount = 0;
        $response->type = 0;//	0 普通支付成功 1 跳转参团详情页 2 家具品类收货设置
        $response->option_type = 1;//	1 逛商场 2 领取红包
        $response->address_id = 0;//	收货人地址薄id
        $orderNos = [];
        $checkHeavy = 0;
        $currentOrderNo = '';
        $currentInfo = [];
        try {
            $isParentNo = OrderNo::isParentNo($orderNo);
            if (!$isParentNo) {//子订单
                $info = \Biz\model\trade\Order::getOrderInfoFromMaster($orderNo);
                array_push($orderNos, $orderNo);
            } else {
                $info = OrderParent::getOrderParentInfoFromMaster($orderNo);
                $orderNos = \Biz\model\trade\Order::getOrderNoList($orderNo);
            }
            $response->pay_amount = isset($info['pay_amount']) ? $info['pay_amount'] : 0;
            $order_type = isset($info['order_type']) ? $info['order_type'] : 0;

            switch ($order_type) {
                case \Biz\model\trade\Order::ORDER_TYPE_PING_TUAN:
                    $response->type = 1;//	0 普通支付成功 1 跳转参团详情页 2 家具品类收货设置
                    $response->team_join_info = Group::getTeamId($orderNo, $uid);
                    break;
                default:
                    //todo 家具品类判断
                    $checkHeavy = OrderInfo::checkHeavyGoodsByOrderNo($orderNos);
                    if ($checkHeavy > 0) {
                        $response->type = 2;
                        $currentOrderNo = current($orderNos);
                        $currentInfo = \Biz\model\trade\Order::getOrderByOrderNo($currentOrderNo);
                        $response->address_id = isset($currentInfo['address_id']) ? $currentInfo['address_id'] : 0;
                    }

                    $redPacket = RedPackets::getPacketInfoByOrder($uid, $orderNo);
                    if ($redPacket) {
                        $response->option_type = 2;//	1 逛商场 2 领取红包
                        $response->red_packet = [
                            'title'  => isset($redPacket['title']) ? $redPacket['title'] : '',
                            'remark' => isset($redPacket['remark']) ? $redPacket['remark'] : '',
                        ];
                    }
                    break;
            }
            Log::info('订单支付成功页面debug', compact('response', 'uid', 'orderNo', 'orderNos', 'checkHeavy', 'currentOrderNo', 'currentInfo'));
        } catch (\Exception $e) {
            $trace = [
                'file'    => $e->getFile(),
                'line'    => $e->getLine(),
                'message' => $e->getMessage(),
            ];
            Log::warning('订单支付成功页面debug', compact('trace', 'uid', 'orderNo', 'orderNos', 'checkHeavy'));
        }
        return $response;
    }

    /**
     * 微信支付宝支付
     * @param $uid
     * @param $isPad
     * @param $orderNo
     * @param $payWay
     * @return $result
     * @throws \Exception
     */
    public static function courseOrder($uid, $orderNo, $payWay)
    {
        //获取订单信息
        $orderInfo = CourseOrder::getCashierAmount($orderNo);
        if ($uid != $orderInfo['uid']) {
            throw new \Exception('订单信息与当前用户不匹配');
        }
        //判断用户是否已经购买
        $hasOrderInfo = mCourseOrder::getByWhere([
            'course_id'    => $orderInfo['course_id'],
            'uid'          => $uid,
            'order_status' => mCourseOrder::STATUS_SUCCESS
        ]);
        //已购买直接返回
        if ($hasOrderInfo) {
            return [
                'order_no' => $hasOrderInfo['order_no'],
                'success'  => 1
            ];
        }
        $isPaid = Pay::checkOrderPayStatus($orderNo, Pay::_PAY_ORDER_TYPE_COURSE);
        //更改订单状态
        $success = $isPaid;
        if ($isPaid) {
            $success = CourseOrder::createOrder($uid, $orderNo, $payWay, $orderInfo);
        } else {
            CourseOrder::createOrder($uid, $orderNo, $payWay, $orderInfo, mCourseOrder::STATUS_NORMAL);
            CourseOrder::addOrderLog($orderNo, $uid, mCourseOrderLog::LOG_TYPE_PAY_ERROR, ['pay_way' => $payWay]);
            Log::pay_courseOrder_warning('付费课订单未支付或支付失败', $orderNo, [
                'order_no' => $orderNo,
                'is_paid'  => $isPaid,
                'uid'      => $uid,
                'pay_way'  => $payWay,
            ]);
        }
        return [
            'order_no'   => $orderNo,
            'pay_amount' => $orderInfo['pay_amount'],
            'success'    => intval($success)
        ];
    }

    /**
     * 微信支付宝支付
     * @param $uid
     * @param $orderNo
     * @param $payWay
     * @return array $result
     * @throws \Exception
     */
    public static function packageOrder($uid, $orderNo, $payWay): array
    {
        $isPaid = Pay::checkOrderPayStatus($orderNo, Pay::_PAY_ORDER_TYPE_PACKAGE);
        $packageId = \Biz\service\package\PackageOrder::getPackageIdByOrderNo($orderNo);
        $price = \Biz\service\package\PackageOrder::PACKAGES[$packageId]['price'];
        //更改订单状态
        $success = $isPaid;
        if ($isPaid) {
            $success = \Biz\service\package\PackageOrder::createOrder($uid, $orderNo, $payWay);
            $link = \Biz\tools\helper\Common::formatFullScreenLink(\Doraemon\tools\Hhzurl::h5PackagePurchase($orderNo));
            if ($packageId == \Biz\service\package\PackageOrder::PACKAGE_ID_3) {
                $link = '';
            }
            return [
                'order_no' => $orderNo,
                'pay_amount' => $price,
                'link' => $link,
                'success' => intval($success)
            ];
        } else {
            \Biz\service\package\PackageOrder::createOrder($uid, $orderNo, $payWay, \Biz\model\package\PackageOrder::STATUS_FAIL);
            $log = [
                'log_data' => json_encode(['uid' => $uid, 'pay_way' => $payWay], JSON_UNESCAPED_UNICODE),
                'log_type' => PackageOrderLog::LOG_TYPE_6,
                'log' => '支付失败',
                'order_no' => $orderNo,
            ];
            PackageOrderLog::add($log);
            Log::info('新人礼包支付失败', ['order_no' => $orderNo, 'is_paid' => $isPaid, 'uid' => $uid, 'pay_way' => $payWay,]);
            return [
                'order_no' => $orderNo,
                'pay_amount' => $price,
                'success' => intval($success)
            ];
        }
    }

    public static function courseTilesOrder($uid, $orderNo)
    {
        //获取订单信息
        $orderInfo = CourseOrder::getCashierAmount($orderNo);
        //扣减瓦片
        $result = Tiles::consumeTiles($uid, $orderInfo);
        if (!$result) {
            throw new \Exception('扣减瓦片失败');
        }
        //创建课程订单
        $result = CourseOrder::createOrder($uid, $orderNo, Pay::_PAY_ORDER_TYPE_TILES, $orderInfo);
        CourseOrder::callbackPaySucc($orderInfo['order_no'], pTiles::_PAY_WAYS_TILES, $orderInfo['order_no'], $orderInfo['pay_amount'], date('Y-m-d H:i:s'));
        return [
            'order_no'   => $orderNo,
            'pay_amount' => $orderInfo['pay_amount'],
            'success'    => intval($result)
        ];
    }

    /**
     * IAP 支付
     * @param $uid
     * @param $orderNo
     * @param $payWay
     * @param $orderType
     * @param $receiptData
     * @return $result
     * @throws \Exception
     */
    public static function courseIAPOrder($uid, $orderNo, $receiptData)
    {
        Log::info('付费课订单order_no:' . $orderNo . '#uid:' . $uid . '#苹果iap验证receipt-data信息:' . $receiptData);
        $iapData = IAP::validReceiptData($uid, $receiptData, $orderNo);
        return CourseOrder::createOrderByIap($uid, $orderNo, $iapData);
    }

    /**
     * IAP 充值
     * @param $uid
     * @param $orderNo
     * @param $payWay
     * @param $orderType
     * @param $receiptData
     * @return $result
     * @throws \Exception
     */
    public static function TilesIAPOrder($uid, $receiptData)
    {
        $iapData = IAP::validReceiptData($uid, $receiptData);
        return Tiles::topupBllance($uid, $iapData);
    }

}